//
//  MALHJieSongTableController.m
//  meiang_edu
//
//  Created by hfcb on 2018/9/14.
//  Copyright © 2018年 com.meiang.meiang_edu. All rights reserved.
//

#import "MALHJieSongTableController.h"
#import "MAJiGouModel.h"
#import "MABabyModel.h"
#import <CoreImage/CoreImage.h>
#import "NSString+Js.h"

@interface MALHJieSongTableController ()
@property (weak, nonatomic) IBOutlet UIView *footerView;
@property (weak, nonatomic) IBOutlet UITextField *nameTF;

@property (weak, nonatomic) IBOutlet UIImageView *qrIcon;
@property (weak, nonatomic) IBOutlet UILabel *dateLabel;
@property (weak, nonatomic) IBOutlet UITextField *phoneTF;
@property (weak, nonatomic) IBOutlet UIButton *btn;

/** babyModels */
@property(nonatomic,strong) NSMutableArray *babyModels;

@end

@implementation MALHJieSongTableController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupBasic];
    
    [self loadBabyData];
}

- (void)setupBasic {
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 4)];
    self.tableView.separatorInset = UIEdgeInsetsMake(0, 999, 0, 0);
    
    NSString *dateStr = [[NSDate date] wj_stringWithFormat:@"yyyy-MM-dd"];
    self.dateLabel.text = dateStr;
    
    self.btn.enabled = NO;
    self.btn.backgroundColor = PROJECT_GRAY_COLOR;
}


- (void)loadBabyData {
    MAUserInfo *userinfo = [MAUserInfoTool userinfo];
    //    if (!userinfo.token) {
    //        [MBManager showBriefAlert:@"登录状态已过期,请重新登录"];
    //        return;
    //    }
    [MBManager showLoading];
    DLog(@"%@",self.title);
    [ZBRequestManager requestWithConfig:^(ZBURLRequest *request) {
        request.requestSerializerType = ZBHTTPRequestSerializer;
        request.URLString = [NSString stringWithFormat:@"%@%@?entity_type=familychildbyorg&status=1",BASE_LISTENTITY_LIST,self.jigouModel.ID];
        request.methodType = ZBMethodTypeGET;
        [request setValue:userinfo.token forHeaderField:@"token"];
        request.apiType = ZBRequestTypeRefresh;
    } success:^(id responseObject, apiType type) {
        [MBManager hideAlert];
        // 解析数据
        NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        DLog(@"%@",dataDict);
        NSInteger code = [dataDict[@"msgcode"] integerValue];
        if (code == 1) { // 请求成功
            [MBManager hideAlert];
            self.babyModels = [MABabyModel mj_objectArrayWithKeyValuesArray:dataDict[@"value"]];
        } else {
            [MBManager showBriefAlert:dataDict[@"message"]];
        }
    } failure:^(NSError *error) {
        DLog(@"%@",error);
        
    } finished:^(id responseObject, apiType type, NSError *error, BOOL isCache) {
        if (isCache==YES) {
            DLog(@"使用了缓存");
        }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)tfValueChanged:(UITextField *)sender {
    DLog(@"");
    if (self.nameTF.text.length && self.phoneTF.text.length) {
        self.btn.enabled = YES;
        self.btn.backgroundColor = PROJECT_DEFAULT_COLOR;
    } else {
        self.btn.enabled = NO;
        self.btn.backgroundColor = PROJECT_GRAY_COLOR;
    }
}
- (IBAction)btnDidClick {
    if (!self.babyModels.count) {
        [MBManager showBriefAlert:@"宝宝列表为空"];
        return;
    }
    NSString *name = self.nameTF.text;
    NSString *phone = self.phoneTF.text;
    if (phone.length != 11) {
        [MBManager showBriefAlert:@"手机号码填写不规范"];
        return;
    }
    // 1.创建过滤器 -- 苹果没有将这个字符封装成常量
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    
    // 2.过滤器恢复默认设置
    [filter setDefaults];
    
    // 3.给过滤器添加数据(正则表达式/帐号和密码) -- 通过KVC设置过滤器,只能设置NSData类型
    NSString *str = [NSString stringWithFormat:@"temp,%@,%@",name,phone];
    for (MABabyModel *model in self.babyModels) {
        str = [str stringByAppendingString: [NSString stringWithFormat:@",%@",model.ID]];
    }
    NSString *dataString = str;
    NSData *data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
    [filter setValue:data forKeyPath:@"inputMessage"];
    
    // 4.获取输出的二维码
    CIImage *outputImage = [filter outputImage];
    
    // 5.显示二维码
    self.qrIcon.image = [self createNonInterpolatedUIImageFormCIImage:outputImage withSize:144];
    self.footerView.hidden = NO;
    
    // 添加临时接送人 安排接送
    [self anpaiJieSong];
}

- (void)anpaiJieSong {
    MAUserInfo *userinfo = [MAUserInfoTool userinfo];
    //    if (!userinfo.token) {
    //        [MBManager showBriefAlert:@"登录状态已过期,请重新登录"];
    //        return;
    //    }
    [MBManager showLoading];
    //    "sender": "",//接送人key 临时接送人 客户端生成guid
    //    "ch_key": "",//孩子key
    //    "org_key": "",//机构key
    //    "dates": "",//日期数组
    //    "usname": "",//接送人姓名
    //    "phone": ""//接送人联系电话
    MABabyModel *model = [self.babyModels firstObject];
    NSMutableDictionary *body = [NSMutableDictionary dictionary];
    body[@"sender"] = [NSString uuidString];
    body[@"ch_key"] = model.ID;
    body[@"org_key"] = self.jigouModel.ID;
    body[@"dates"] = [@[[[NSDate date] wj_dateStringFormatYMD]] mj_JSONString];
    body[@"usname"] = self.nameTF.text;
    body[@"phone"] = self.phoneTF.text;
    
    NSError *error;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:body options:0 error:&error];
    
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:SENDER_PLANS_ADD parameters:nil error:nil];
    
    [req setValue:@"application/text" forHTTPHeaderField:@"Content-Type"];
    
    [req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    
    [req setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
    
    [[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        [MBManager hideAlert];
        if (!error) {
            DLog(@"Reply JSON: %@", responseObject);
            NSInteger msgcode = [responseObject[@"msgcode"] integerValue];
            NSString *message = responseObject[@"message"];
            if (msgcode == 1) {
                [MBManager showBriefAlert:message];
            } else {
                [MBManager showBriefAlert:message];
            }
        } else {
            DLog(@"Error: %@, %@, %@", error, response, responseObject);
            [MBManager showBriefAlert:@"网络错误"];
        }
    }] resume];
}

/**
 *  根据CIImage生成指定大小的UIImage
 *
 *  @param image CIImage
 *  @param size  图片宽度
 */
- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size
{
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    
    // 1.创建bitmap;
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    
    // 2.保存bitmap到图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    return [UIImage imageWithCGImage:scaledImage];
}

#pragma mark - getter & setter
- (NSMutableArray *)babyModels {
    if (_babyModels == nil) {
        _babyModels = [NSMutableArray array];
    }
    return _babyModels;
}
@end
